package team.szm.scd.controller;

import org.springframework.web.bind.annotation.*;
import team.szm.scd.database.dto.RequestWrapper;
import team.szm.scd.database.dto.Result;
import team.szm.scd.database.dto.UserLogin;
import team.szm.scd.database.entity.Doctor;
import team.szm.scd.database.entity.DoctorWorkTime;
import team.szm.scd.database.vo.DoctorVO;
import team.szm.scd.service.interfaces.IDoctorService;
import team.szm.scd.service.interfaces.ILoginService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/doctor")
public class DoctorController {
    @Resource
    IDoctorService service;
    @Resource
    ILoginService loginService;
    public static class FailMessages extends UserController.FailMessages {
        public final static String NO_ID = "请输入工号！";
        public final static String NO_DOCTOR_FIND = "请检查工号是否正确，或者请先注册！";
    }

    @PostMapping("/login")
    @ResponseBody
    public Result<DoctorVO> login(@RequestBody UserLogin login, HttpSession session) {
        Object verify_code = session.getAttribute("verify_code");
        if (!(verify_code instanceof String)) {
            return Result.fail(FailMessages.NO_VERIFY_CODE_IN_SESSION, null);
        } else if (!verify_code.equals(login.getVerify_code())) {
            return Result.fail(FailMessages.WRONG_VERIFY_CODE, null);
        }
        if (login.getId() == null) {
            return Result.fail(FailMessages.NO_ID, null);
        }
        DoctorVO doctor = service.fromId(login.getId());
        if (doctor == null) {
            return Result.fail(FailMessages.NO_DOCTOR_FIND, null);
        } else if (doctor.getPassword().equals(login.getPassword())) {
            session.setAttribute(Doctor.DOCTOR_SESSION_STR, doctor);
            return Result.success(doctor);
        } else {
            return Result.fail(UserController.FailMessages.WRONG_PASSWORD, null);
        }
    }

    @GetMapping("/now")
    @ResponseBody
    public Result<Doctor> getNowDoctor(HttpSession session) {
        Doctor doctor = loginService.getLoginDoctor(session);
        if (doctor == null) {
            return Result.needLogin();
        }
        return Result.success(doctor);
    }

    @PostMapping("/work_time")
    @ResponseBody
    public Result<List<DoctorWorkTime>>
    login(@RequestBody RequestWrapper<String> id, HttpSession session) {
        if (loginService.noUserAndNoDoctorLogin(session)) {
            return Result.needLogin();
        }
        return Result.success(service.workTimesFromId(id.value));
    }

}
